package com.ouyunc.rpc.config;

import com.ouyunc.common.constant.CommonConstant;
import com.ouyunc.common.utils.ThreadPoolUtil;
import feign.RequestInterceptor;
import feign.RequestTemplate;
import org.apache.commons.lang3.StringUtils;
import org.springframework.context.annotation.Configuration;
import org.springframework.web.context.request.RequestContextHolder;
import org.springframework.web.context.request.ServletRequestAttributes;

import javax.servlet.http.HttpServletRequest;

/**
 * feign 调用传递参数：token
 */
@Configuration
public class FeignRequestInterceptor implements RequestInterceptor {
    @Override
    public void apply(RequestTemplate requestTemplate) {
        // 注意：如果使用requestAttribute需要考虑多线程情况下获取token，进行传递
        ServletRequestAttributes requestAttributes =(ServletRequestAttributes) RequestContextHolder.getRequestAttributes();
        if (requestAttributes != null){
            HttpServletRequest request = requestAttributes.getRequest();
            String accessToken = request.getHeader(CommonConstant.ACCESS_TOKEN);
            //如果token为空，则可能是多线程调用，去线程共享类去尝试获取token
            if (StringUtils.isBlank(accessToken)){
                accessToken = (String) ThreadPoolUtil.ttlThreadLocal.get();
            }
            requestTemplate.header(CommonConstant.ACCESS_TOKEN,accessToken);
        }
    }
}
